package cn.shop.gameapi.consumer;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpUtil;
import cn.shop.gameapi.model.GatewaySecret;
import cn.shop.msgs.PartitionDeleteMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.util.stream.Collectors;

import static cn.shop.gameapi.model.SqlContent.SELECT_SECRET_IP_UID;

/**
 * @author : 李一涵
 * @date : Created in 2021-12-17 14:19
 * @description :
 */
@RocketMQMessageListener(topic = PartitionDeleteMsg.TOPIC, consumerGroup = "partition-delete-consumer", selectorExpression = PartitionDeleteMsg.TAG)
public class PartitionDeleteConsumer implements RocketMQListener<PartitionDeleteMsg> {
    private static final Logger LOG = LoggerFactory.getLogger(PartitionDeleteConsumer.class);

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void onMessage(PartitionDeleteMsg msg) {
        LOG.info("收到消息:{}", msg);
        if (msg == null) {
            return;
        }
        try {
            sendPartition(msg);
        } catch (Exception e) {
            LOG.warn("删除分区失败", e);
        }
    }

    private void sendPartition(PartitionDeleteMsg msg) {
        GatewaySecret secret = null;
        try {
            secret = jdbcTemplate.queryForObject(SELECT_SECRET_IP_UID, new BeanPropertyRowMapper<>(GatewaySecret.class), msg.getIp(), msg.getUid());
        } catch (EmptyResultDataAccessException ignored) {}
        LOG.info("开始删除分区：{} {} {}", msg.getIp(), msg.getPort(), msg);
        String url = "http://" + msg.getIp() + ":" + msg.getPort() + "/gateway/api/partition/remove";
        String json = HttpUtil.createPost(url)
                .header("secret", secret != null ? secret.getSecret() : "")
                .contentType(ContentType.TEXT_PLAIN.getValue())
                .body(msg.getIds().stream().map(String::valueOf).collect(Collectors.joining(",")))
                .execute()
                .body();
        if (StrUtil.isBlank(json)) {
            LOG.warn("删除分区秘钥无效");
        } else {
            LOG.info(json);
        }
    }
}
